<script setup>
defineOptions({ name: 'contactForm' })
import 'vant/es/toast/style'
import { showFailToast, showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'
import { areaList } from '@vant/area-data'
import {
  getAddressDetail,
  updateAddress,
  addAddress,
  delAddress
} from '@/api/address.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps(['id'])
const isEdit = ref(Boolean(props.id))
onMounted(async () => {
  if (isEdit.value) {
    const res = await getAddressDetail(props.id)
    fd.value = {
      ...res,
      tel: res.phone,
      isDefault: Boolean(res.is_default),
      addressDetail: res.address
    }
  }
})

const fd = ref({
  name: '',
  tel: '',
  province: '',
  city: '',
  county: '',
  addressDetail: '',
  areaCode: '',
  isDefault: false
})

const onSave = async (val) => {
  const params = {
    name: val.name,
    address: val.addressDetail,
    phone: val.tel,
    province: val.province,
    city: val.city,
    county: val.county,
    is_default: Number(val.isDefault)
  }
  if (isEdit.value) {
    const { status } = await updateAddress(+props.id, params)
    status === 204 ? showSuccessToast('更新成功') : showFailToast('更新失败')
  } else {
    const { status } = await addAddress(params)
    status === 201 ? showSuccessToast('添加成功') : showFailToast('添加失败')
  }
}
const onDelete = async () => {
  const { status } = await delAddress(props.id)
  status === 204
    ? showSuccessToast('删除成功') && router.go(-1)
    : showFailToast('删除失败')
}
</script>

<template>
  <div>
    <van-address-edit
      :address-info="fd"
      :area-list="areaList"
      show-delete
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>
